/**
 * Webservices to manage modules from the android app
 */
var database = require('../../core/database');

function requireModule (moduleName) {
	var serverRoot = '../../';
	return require(serverRoot + 'modules/' + moduleName + '/module');
}

exports.listModules = function (req, res) {

	database.getAllModules(function(modules) {
		if (modules == null) {
			res.end('[]');
		} else {
			res.json(modules);
		}
	});
}

exports.create = function(req, res) {
	var moduleName = req.params.moduleName;
	
	var module = requireModule(moduleName);
	var paramObj = new Object();
	
	for (var i=0;i<module.requirements.length; i++) {
		var curRequirement = module.requirements[i];
		if (req.body[curRequirement] == undefined) {
			// A dependency is missing
			res.end('{"code":"missing_dependency"}\n');
			return;
		}
	}
	
	module.create(moduleName, req.body, function(id) {
		res.json({'code': 'OK', 'id': id});
	});
}

/**
 * Get the existing sensors that can be used to fulfill the requirements of the given module
 */
exports.getSources = function(req, res, next) {
	var moduleName = req.params.moduleName;
	console.log('Request handler getSources was called for module ' + moduleName);
	
	var module = requireModule(moduleName);
	

	// List containing the sensor description with IDs of sensors corresponding to this description
	var sensorList = {};
	// index to go through the module requirements
	var i = 0;

	var respond = function() {
		res.send(sensorList);
	}

	if(module.requirements.length < 1) {
		respond();
	}

	var callbackDB = function(ids) {
		sensorList[module.requirements[i]] = ids;

		i++;
		// Replacing a for loop to go through the requirements array
		if (i < module.requirements.length) {
			// recursive callback makes me wanna throw up
			database.getSensorIDs(module.requirements[i], callbackDB);
			// if we're done with the sensors requirements
		} else {
			respond();
		}
	}

	database.getSensorIDs(module.requirements[i], callbackDB);

	// not working, that's why I do the recursive callback, the value of i does not exists in the callback function
	/*
		for (i = 0; i < module.requirements.length; i++) {
			database.getSensorIDs(module.requirements[i], function(ids) {
				sensorList[module.requirements[i]] = ids;
				console.log("anon. " + plop + ' ' + module.requirements[0] + " " + JSON.stringify(sensorList));
			});
		}
*/
}

/*
 * Dummy form for testing purpose
 */
exports.form = function(req, res) {
	console.log("Request handler 'form' was called.");
	var body = '<html>' +
		'<head>' +
		'<meta http-equiv="Content-Type" ' +
		'content="text/html; charset=UTF-8" />' +
		'</head>' +
		'<body>' +
		'<p>Request sources by hand:</p>' +
		'<form action="/modules/sources" method="post">' +
		'<input type="text" name="moduleName">' +
		'<input type="submit" value="Request" />' +
		'</form>' +
		'</body>' +
		'</html>';
	res.send(body);
};

